#include "serial.h"
#include <QDebug>

Serial::Serial(QObject *parent) : QObject(parent)
{
    isConnected = false;
    port = new QSerialPort(this);
    connect(port, SIGNAL(readyRead()), this, SLOT(onRX()));

    frameTimer = new QTimer(this);
    frameTimer->setInterval(10);
    frameTimer->setSingleShot(true);
    connect(frameTimer, SIGNAL(timeout()), this, SLOT(onFrameTimeout()));
}

bool Serial::open(const QString &dev, QSerialPort::BaudRate baud)
{
    bool ret;
    int timeoutMs;

    port->setPortName(dev);
    port->setBaudRate(baud);
    port->setDataBits(QSerialPort::Data8);
    port->setStopBits(QSerialPort::OneStop);
    port->setParity(QSerialPort::NoParity);
    port->setFlowControl(QSerialPort::NoFlowControl);

    ret = port->open(QIODevice::ReadWrite);
    if(ret)
    {
        timeoutMs = (4 * 10 * 1000) / baud;     // 4个字符时间间隔作为帧间隔
        frameTimer->setInterval(timeoutMs + 1); // +1防止时长为0
        qDebug() << "Open port:" << dev << "success.";
    }
    else
    {
        qDebug() << "Open port:" << dev << "fail:" << port->error() << "!";
    }

    return ret;
}

Serial::~Serial()
{
    port->close();
    frameTimer->stop();

    delete port;
    delete frameTimer;
}

void Serial::setFrameGap(int msec)
{
    frameTimer->setInterval(msec);
}

bool Serial::send(const QByteArray &data)
{
    return (port->write(data) == data.size()) ? true : false;
}

void Serial::onFrameTimeout()
{
    if(rxData.size() > 0)
    {
        QByteArray frame = rxData;
//        qDebug() << port->portName() << "RX:" << frame.toHex();
        emit frameIn(frame);
        rxData.clear();
    }
}

void Serial::onRX()
{
    frameTimer->start();
    if(rxData.size() < 100)
    {
        rxData += port->readAll();
    }
}
